# 你是ps1助手只智能体，现在让你制作一款提效工具
# 功能如下：

# 1.打开注册表编辑器找到这个路径：计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography

# 2.修改注册表项目：MachineGuid，修改数值数据:c7c41bd3-9821-45cd-bab1-469f9825d9f8,保留数值格式并随机生成。

# 3.修改该注册表好，生成备份文件到C:\Users\Administrator\AppData\Roaming\Cursor\User\globalStorage\backups，没有改目录则创建，备份文件名为MachineGuid_20250207_151428.txt加日期格式。

# 4.找到路径:C:\Users\Administrator\AppData\Roaming\Cursor\User\globalStorage\storage.json更改以下这4个数值，并保留格式，数值随机生成

#  "telemetry.machineId": "e8a0e018a2918c291a4b84faec501ae826589ffafe53b3626c1d1de8cc82202d",
#     "telemetry.macMachineId": "4c2c9c4f4ed94e5e6f68ad87d9e3cd22ae24cf98f9e893fb71c4dffbf88537d8",
#     "telemetry.sqmId": "{4B5F7F57-EFF7-405F-81DD-11CB218CF464}",
#     "telemetry.devDeviceId": "37c00bd4-fc81-4981-a8ab-4cb55eaabe77",

# 5.将原来的C:\Users\Administrator\AppData\Roaming\Cursor\User\globalStorage\storage.json文件备份到C:\Users\Administrator\AppData\Roaming\Cursor\User\globalStorage\backups目录下，备份文件名:storage_20250207_151428.json的日期格式

# 6.打印相应的的输出，并输出报错信息，方便调试




# 设置严格模式和错误处理
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

# 首先确保文件是以 UTF8-BOM 格式保存的
function Write-Log {
    param(
        [string]$Message,
        [string]$Type = "Info"
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    switch ($Type) {
        "Info"    { Write-Host "[$timestamp] $Message" -ForegroundColor White }
        "Success" { Write-Host "[$timestamp] $Message" -ForegroundColor Green }
        "Error"   { Write-Host "[$timestamp] Error: $Message" -ForegroundColor Red }
        "Warning" { Write-Host "[$timestamp] Warning: $Message" -ForegroundColor Yellow }
    }
}

try {
    # 检查管理员权限
    $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    if (-not $isAdmin) {
        Write-Log "Please run this script as Administrator!" "Error"
        pause
        exit 1
    }

    # 设置输出编码为UTF8
    $OutputEncoding = [System.Text.Encoding]::UTF8
    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    $PSDefaultParameterValues['*:Encoding'] = 'utf8'
    chcp 65001 | Out-Null

    # 添加标题
    $host.UI.RawUI.WindowTitle = "Cursor ID Reset Tool"

    # 设置日期时间格式
    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"

    # 定义路径
    $BACKUP_DIR = Join-Path $env:APPDATA "Cursor\User\globalStorage\backups"
    $STORAGE_FILE = Join-Path $env:APPDATA "Cursor\User\globalStorage\storage.json"
    $registryPath = "HKLM:\SOFTWARE\Microsoft\Cryptography"

    # 创建备份目录
    if (-not (Test-Path $BACKUP_DIR)) {
        New-Item -ItemType Directory -Path $BACKUP_DIR -Force | Out-Null
        Write-Log "Backup directory created: $BACKUP_DIR" "Success"
    }

    # 检查 Cursor 是否正在运行
    $cursorProcess = Get-Process "Cursor" -ErrorAction SilentlyContinue
    if ($cursorProcess) {
        Write-Log "Please close Cursor before continuing" "Warning"
        $response = Read-Host "Do you want to close Cursor automatically? (Y/N)"
        if ($response -eq 'Y' -or $response -eq 'y') {
            $cursorProcess | Stop-Process -Force
            Start-Sleep -Seconds 2
            Write-Log "Cursor has been closed" "Success"
        }
        else {
            Write-Log "Operation cancelled" "Warning"
            exit 0
        }
    }

    # 生成新的GUID和ID
    $NEW_MACHINE_GUID = [guid]::NewGuid().ToString().ToLower()
    $NEW_MACHINE_ID = [System.BitConverter]::ToString([System.Security.Cryptography.HashAlgorithm]::Create('SHA256').ComputeHash([System.Text.Encoding]::UTF8.GetBytes([System.Guid]::NewGuid().ToString()))).Replace('-','').ToLower()
    $NEW_MAC_ID = [System.BitConverter]::ToString([System.Security.Cryptography.HashAlgorithm]::Create('SHA256').ComputeHash([System.Text.Encoding]::UTF8.GetBytes([System.Guid]::NewGuid().ToString()))).Replace('-','').ToLower()
    $NEW_SQM_ID = "{$([guid]::NewGuid().ToString().ToUpper())}"
    $NEW_DEVICE_ID = [guid]::NewGuid().ToString()

    # 备份并修改注册表
    $backupFile = Join-Path $BACKUP_DIR "MachineGuid_$timestamp.txt"
    reg export "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" $backupFile /y | Out-Null
    Write-Log "Registry backup successful: $backupFile" "Success"

    Set-ItemProperty -Path $registryPath -Name 'MachineGuid' -Value $NEW_MACHINE_GUID -Type String -Force
    
    $CURRENT_GUID = (Get-ItemProperty -Path $registryPath).MachineGuid
    if ($CURRENT_GUID -ne $NEW_MACHINE_GUID) {
        throw "Registry modification verification failed"
    }
    Write-Log "Registry modified successfully" "Success"

    # 处理storage.json文件
    if (-not (Test-Path $STORAGE_FILE)) {
        throw "storage.json file not found"
    }

    # 备份storage.json
    $storageBackup = Join-Path $BACKUP_DIR "storage_$timestamp.json"
    Copy-Item $STORAGE_FILE $storageBackup -Force
    Write-Log "storage.json backup successful: $storageBackup" "Success"

    # 更新JSON文件
    $json = Get-Content $STORAGE_FILE -Raw | ConvertFrom-Json
    $json.'telemetry.machineId' = $NEW_MACHINE_ID
    $json.'telemetry.macMachineId' = $NEW_MAC_ID
    $json.'telemetry.sqmId' = $NEW_SQM_ID
    $json.'telemetry.devDeviceId' = $NEW_DEVICE_ID
    $json | ConvertTo-Json -Depth 100 | Set-Content $STORAGE_FILE -Force
    Write-Log "storage.json updated successfully" "Success"

    # 显示操作摘要
    Write-Log "`nOperation Summary:" "Success"
    Write-Host "New MachineGuid: $NEW_MACHINE_GUID" -ForegroundColor Cyan
    Write-Host "New MachineId:   $NEW_MACHINE_ID" -ForegroundColor Cyan
    Write-Host "New MacId:       $NEW_MAC_ID" -ForegroundColor Cyan
    Write-Host "New SQMId:       $NEW_SQM_ID" -ForegroundColor Cyan
    Write-Host "New DeviceId:    $NEW_DEVICE_ID" -ForegroundColor Cyan
    Write-Host "Backup Location: $BACKUP_DIR" -ForegroundColor Cyan

    Write-Log "`nAll operations completed successfully" "Success"
}
catch {
    Write-Log $_.Exception.Message "Error"
}
finally {
    Write-Log "Press any key to exit..." "Info"
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}